from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from itsdangerous import BadData

from oauth import constants


def generate_openid_access_token(openid):
    s = Serializer(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)
    data = {'openid': openid}
    access_token = s.dumps(data)
    return access_token.decode()


def check_openid_access_token(access_token):
    s = Serializer(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)

    try:
        token_dict = s.loads(access_token)
    except BadData:
        return None
    else:
        return token_dict['openid']
